import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import React, { Ref, useRef, useEffect, useMemo, useState } from 'react';
import { RuleManageAPI } from '../common/type';
import { Col, Form, Input, Row, Select, message, Button, Spin } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import { ILoadMapTypeAll } from '@/common';
import MyIcon from '@/components/MyIcon';
import { UploadFormCommon } from '@/components/UploadForm';
import { getLoadMapList, getTenantID } from '@/utils';
import { editRuleServices, detailRuleServices, saveRuleServices } from '../services/UpdateService';
export const UpdateModal: React.FC<RuleManageAPI.IUpdateModalAPI> = ({ curRes, onClose, reloadRequest, checkRowsInfo }) => {
  /**弹框的ref*/
  const UpdateModalRef: Ref<IOneModalRef> = useRef(null);

  /** form表单实例 */
  const [updateForm] = Form.useForm();

  /** 获取数据字典loadMdicMap */
  const { loadMapInfo, mapLoading }: Record<string, any> = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`, //采购方式
  ]);

  /**保存一份 拟采方式 数据*/
  const [procureDraftData, setProcureDraftData] = useState<Record<string, any>[]>([]);

  /**关闭弹窗方法*/
  const onCloseModal = () => {
    if (UpdateModalRef) {
      if (UpdateModalRef.current) {
        if (UpdateModalRef.current.onModalCancel) {
          UpdateModalRef.current.onModalCancel();
        }
      }
    }
  };

  /** 详情接口回调 */
  const detailRuleCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      updateForm?.setFieldsValue({
        ...res?.obj,
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 详情接口 */
  const { detailRuleRun, detailRuleLoading, detailRuleInfo } = detailRuleServices(detailRuleCallback);

  /** 初始化 */
  useEffect(() => {
    if (checkRowsInfo?.id) {
      detailRuleRun({ id: checkRowsInfo?.id });
    }
  }, [checkRowsInfo]);

  /**详情反显数据 */
  useEffect(() => {
    if (detailRuleInfo && detailRuleInfo?.id && loadMapInfo) {
      updateForm?.setFieldsValue({
        ...detailRuleInfo,
      });
      loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`]?.find((item: Record<string, any>) => {
        if (item.id == detailRuleInfo?.procureOrg) {
          setProcureDraftData(item.children);
        }
      });
    }
  }, [detailRuleInfo, loadMapInfo]);

  /**
   * 添加，编辑接口回调
   * */
  const updateCallback = (res: Record<string, any>) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      reloadRequest();
      onCloseModal();
    } else {
      message.error(res?.msg);
    }
  };

  /** 添加接口 */
  const { saveRuleRun, saveRuleLoading } = saveRuleServices(updateCallback);

  /**
   * 编辑接口
   * */
  const { editRuleRun, editRuleLoading } = editRuleServices(updateCallback);

  /** 组织形式选中时 */
  const selectProcureOrg = (value: string) => {
    loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`]?.find((item: Record<string, any>) => {
      if (item.id == value) {
        setProcureDraftData(item.children);
      }
    });
  };

  const footerModal = useMemo(() => {
    return (
      <>
        <Button
          key="back"
          onClick={onCloseModal}
          // icon={<CloseCircleOutlined />}
        >
          {detailRuleInfo?.id ? '取消' : '关闭'}
        </Button>
        {curRes['/purchaseStyleRuleController/add'] && curRes['/purchaseStyleRuleController/edit'] && (
          <Button
            key="submit"
            type="primary"
            loading={saveRuleLoading || editRuleLoading || detailRuleLoading}
            // icon={<SaveOutlined />}
            onClick={() => {
              onSave();
            }}
          >
            {detailRuleInfo?.id ? '确认' : '保存'}
          </Button>
        )}
      </>
    );
  }, [curRes, saveRuleLoading, editRuleLoading, detailRuleLoading, detailRuleInfo]);

  /**点击确定*/
  const onSave = () => {
    updateForm?.validateFields()?.then((values: any) => {
      const payload: Record<string, any> = {
        ...values,
      };

      delete payload?.delegateTime;

      //添加编辑
      if (checkRowsInfo?.id) {
        const editPayload: Record<string, any> = {
          ...payload,
          id: detailRuleInfo?.id,
          versionNum: detailRuleInfo?.versionNum,
        };
        editRuleRun(editPayload);
      } else {
        const addPayload: Record<string, any> = {
          ...payload,
        };

        saveRuleRun(addPayload);
      }
    });
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={UpdateModalRef}
        title={detailRuleInfo?.id ? '编辑采购规则' : '添加采购规则'}
        width={document.body.clientWidth * 0.35}
        onCancel={onClose}
        bodyStyle={{
          padding: '5px 10px',
        }}
        centered
        footer={footerModal}
        confirmLoading={editRuleLoading || saveRuleLoading || detailRuleLoading || mapLoading}
      >
        <Spin spinning={editRuleLoading || saveRuleLoading || detailRuleLoading || mapLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form form={updateForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    name="ruleTitle"
                    label="规则标题"
                    rules={[
                      {
                        required: true,
                        message: '请输入规则标题',
                      },
                    ]}
                  >
                    <Input placeholder="请输入规则标题" allowClear />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    name="ruleInfo"
                    label="规则介绍"
                    rules={[
                      {
                        required: true,
                        message: '请输入规则介绍',
                      },
                    ]}
                  >
                    <Input.TextArea placeholder="请输入规则介绍" maxLength={300} autoSize={{ minRows: 3, maxRows: 5 }} showCount allowClear />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    name="procureOrg"
                    label="组织形式"
                    rules={[
                      {
                        required: true,
                        message: '请选择组织形式',
                      },
                    ]}
                  >
                    <Select placeholder={`请选择组织形式`} allowClear={true} loading={mapLoading} onSelect={selectProcureOrg}>
                      {loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`]?.map((item: any) => {
                        return (
                          <Select.Option key={item?.id} value={item?.id}>
                            <MyIcon style={{ marginRight: 5 }} type="cluster" />
                            {item?.name}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item noStyle shouldUpdate>
                    {({ getFieldValue }) =>
                      getFieldValue('procureOrg') && (
                        <Form.Item
                          name="procureDraft"
                          label="拟采方式"
                          rules={[
                            {
                              required: true,
                              message: '请选择拟采方式',
                            },
                          ]}
                        >
                          <Select placeholder={`请选择拟采方式`} allowClear={true} loading={mapLoading}>
                            {procureDraftData?.map((item: any) => {
                              return (
                                <Select.Option key={item?.id} value={item?.id}>
                                  <MyIcon style={{ marginRight: 5 }} type="profile" />
                                  {item?.name}
                                </Select.Option>
                              );
                            })}
                          </Select>
                        </Form.Item>
                      )
                    }
                  </Form.Item>
                </Col>
                <UploadFormCommon
                  form={updateForm}
                  fileFormName={'bidTempFileURL'}
                  spanCol={24}
                  inRowProportion={24}
                  name={'attachFile'}
                  url={'/purchaseStyleRuleController/uploadFile'}
                  downloadUrl={'/purchaseStyleRuleController/downloadFile'}
                  label="招标范本文件"
                  required={true}
                  accept={'.doc|.docx'}
                  fileFormDelName={'bidTempFileURLDel'}
                  delFunc={() => {}}
                  maxFile={1}
                  defaultFiles={detailRuleInfo?.id ? detailRuleInfo?.bidTempFileURL : null}
                  hintTitle={'且只能上传 1 个！'}
                  fieldBusiPath={'purchase/rule'}
                >
                  上传文件
                </UploadFormCommon>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
